package com.sinopec.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;

import javax.crypto.EncryptedPrivateKeyInfo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sinopec.android.bean.AttDoc;
import com.sinopec.android.util.LogUtil;
import com.sinopec.android.util.StringUtil;
import com.sinopec.android.util.ToastUtil;

/**
* @ClassName: MoreAttDocActivity
* @Description: TODO(更多公文附件)
* @author liuwei
* @date 2012-4-1 下午05:17:45
* 
*/
public class MoreAttDocActivity extends BaseActivity {
	
	public static Dialog dialog;
	public  Context mContext = MoreAttDocActivity.this;
	
	
	/**整个文档视图**/
	ScrollView documet_scroll_layout = null;
	/**附件名称按钮**/
	LinearLayout document_path_layout = null;
	/**附件正文**/
	TextView document_zhengwen_textview = null;
	/**附件名称**/
	TextView document_name_textview = null;
	
	
	LayoutInflater inflater;
	String title = "";
	ArrayList<AttDoc>  attDocList;
	
	//附件 
	String fileUrl=null;
	File file = null;
	String SDPath = Environment.getExternalStorageDirectory()+"/";
	String md5FileName = null;
	String md5FilePath = null;
	
	
	ArrayList<File> fileList = new ArrayList<File>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_att_doc_view);
		title = getIntent().getStringExtra("moreAttDocTitle");
		attDocList = (ArrayList<AttDoc>) getIntent().getSerializableExtra("moreAttDocList");
		initView();
		initAttDoc();
	}
	
	void initView(){
		inflater = getLayoutInflater();
		((TextView)findViewById(R.id.navi)).setText(title);
		documet_scroll_layout = (ScrollView) findViewById(R.id.document_scroll_layout);
		documet_scroll_layout.setVisibility(View.VISIBLE);//设置不可见
		document_path_layout = (LinearLayout) findViewById(R.id.document_path_layout);
		document_path_layout.setVisibility(View.GONE);//默认设置不可见

	}
	void initAttDoc(){

		document_path_layout.setVisibility(View.VISIBLE);
		for(int i=0;i<attDocList.size();i++){
		final	AttDoc attDoc = attDocList.get(i);
			if(attDoc!=null){
				View pathView = inflater.inflate(R.layout.document_detail_filepath_layout, null);
				pathView.setTag(attDoc.getAttFilePath());
				document_zhengwen_textview = (TextView) pathView.findViewById(R.id.document_zhengwen_textview);
				document_name_textview = (TextView) pathView.findViewById(R.id.document_name_textview);
				document_zhengwen_textview.setText("");
				document_name_textview.setText(attDoc.getAttFieleName());
				document_path_layout.addView(pathView, new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.FILL_PARENT,
						LinearLayout.LayoutParams.WRAP_CONTENT));
				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.FILL_PARENT, 5);
				TextView textView = new TextView(this);
				textView.setLayoutParams(layoutParams);
				document_path_layout.addView(textView);
				pathView.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						fileUrl = v.getTag().toString();
						md5FileName = StringUtil.MD5(fileUrl)+fileUrl.substring(fileUrl.lastIndexOf("."));
						md5FilePath = SDPath+md5FileName;
//						ToastUtil.showToast(mContext,fileUrl );
//						
//						ToastUtil.showToast(mContext, md5FilePath);
						
						if(isExist(md5FilePath)){
							//直接
							openFile(new File(md5FilePath));
							return ;
						}else{
							//透明loading进度条
							dialog = new Dialog(mContext,R.style.NobackDialog);  
							dialog.setContentView(R.layout.dialog_loading);  
							TextView loadTip = (TextView) dialog.findViewById(R.id.loadTip);
							loadTip.setText(mContext.getResources().getString(R.string.loadingTip));
							
							dialog.show();
							
							dialog.setOnCancelListener(new OnCancelListener() {
								@Override
								public void onCancel(DialogInterface arg0) {
									LogUtil.printInfo("the dialog is cancel");
									//终止请求进程
								}
							});
							
							new Thread(new Runnable() {
								@Override
								public void run() {
					                HttpClient client = new DefaultHttpClient();  
					                HttpGet get = new HttpGet(fileUrl);  
					                HttpResponse response = null; 
					                FileOutputStream fileOutputStream = null;  
					                InputStream is=null;
					                try {  
					                	response = client.execute(get);
					                	if(response.getStatusLine().getStatusCode()!=200)
										throw new IOException("StatusCode!=200");
					                    HttpEntity entity = response.getEntity();  
					                    long count = 0;
					                	long total = 0;
					                    total = entity.getContentLength();
					                    is = entity.getContent(); 
					                    if (is != null) {  
					  
					                        file = new File(md5FilePath);  
					                        fileOutputStream = new FileOutputStream(file);  
					                          
					                        byte[] buf = new byte[1024];  
					                        int ch = -1;
					                        while ((ch = is.read(buf)) != -1) {
					                        	
					                        	count+=ch;
					                            fileOutputStream.write(buf, 0, ch);
					                        } 
					                        if(count==total)
					                        	mHandler.sendEmptyMessage(0);
					                        fileOutputStream.flush();
					                        if(fileOutputStream!=null)
					                        	fileOutputStream.close();
					                    } else{
					                    	mHandler.sendEmptyMessage(1);
					                    	if(file!=null&&file.exists())file.delete(); 
					                    }
					                } catch (Exception e) {   
					                    e.printStackTrace();
					                    mHandler.sendEmptyMessage(1);
					                    
					                    if(file!=null&&file.exists())file.delete(); 
					        
					                } finally{
										try {
											if(is!=null){
												is.close();
											}
										} catch (IOException e1) {
											e1.printStackTrace();
											mHandler.sendEmptyMessage(1);
							                if(file!=null&&file.exists())file.delete(); 
										}
									}
								}
							}).start();
					 }
					}
				});
			}
		}
	
	}
	
	
	  /**
	 * 打开文件
	 * @param file
	 */ 
	private void openFile(File file){ 
	     
	    Intent intent = new Intent(); 
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	    //设置intent的Action属性 
	    intent.setAction(Intent.ACTION_VIEW); 
	    //获取文件file的MIME类型 
	    String type = getMIMEType(file); 
	   // 设置intent的data和Type属性。 
	    String fileName = file.getName();
	    if(fileName.toLowerCase().endsWith(".svg")||fileName.toLowerCase().endsWith(".gd")&&checkAppIsExist("com.opera.browser")){
	    	intent.setData(Uri.fromFile(file));
	    	intent.setClassName("com.opera.browser","com.opera.Opera"); 
	    }
	    else if((fileName.toLowerCase().endsWith(".doc")||fileName.toLowerCase().endsWith(".docx")
	    		||fileName.toLowerCase().endsWith(".xls")||fileName.toLowerCase().endsWith(".xlsx")
	    		||fileName.toLowerCase().endsWith(".ppt")||fileName.toLowerCase().endsWith(".ppts")
	    		||fileName.toLowerCase().endsWith(".pps")||fileName.toLowerCase().endsWith(".pdf"))&&checkAppIsExist("com.infraware.polarisoffice")
	    ){
	    	intent.setData(Uri.fromFile(file));
	    	intent.setClassName("com.infraware.polarisoffice","com.infraware.polarisoffice.OfficeLauncherActivity"); 
	    }
	    else
	    {
	    	intent.setDataAndType(Uri.fromFile(file), type); 
	    }
	    //跳转 
	    startActivity(intent);   

	    fileList.add(file);
	     
	} 
	 
	/**
	 * 根据文件后缀名获得对应的MIME类型。
	 * @param file
	 */ 
	private String getMIMEType(File file) { 
	     
	    String type="*/*"; 
	    String fName = file.getName(); 
	    //获取后缀名前的分隔符"."在fName中的位置。 
	    int dotIndex = fName.lastIndexOf("."); 
	    if(dotIndex < 0){ 
	        return type; 
	    } 
	    /* 获取文件的后缀名*/ 
	    String end=fName.substring(dotIndex,fName.length()).toLowerCase(); 
	    if(end=="")return type; 
	    //在MIME和文件类型的匹配表中找到对应的MIME类型。 
	    for(int i=0;i<MIME_MapTable.length;i++){ //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？ 
	        if(end.equals(MIME_MapTable[i][0])) 
	            type = MIME_MapTable[i][1]; 
	    }        
	    return type; 
	} 
	
	String [][] MIME_MapTable={ 
            //{后缀名，MIME类型} 
            {".3gp",    "video/3gpp"}, 
            {".apk",    "application/vnd.android.package-archive"}, 
            {".asf",    "video/x-ms-asf"}, 
            {".avi",    "video/x-msvideo"}, 
            {".bin",    "application/octet-stream"}, 
            {".bmp",    "image/bmp"}, 
            {".c",  "text/plain"}, 
            {".class",  "application/octet-stream"}, 
            {".conf",   "text/plain"}, 
            {".cpp",    "text/plain"}, 
            {".doc",    "application/msword"}, 
            {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, 
            {".xls",    "application/vnd.ms-excel"},  
            {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, 
            {".exe",    "application/octet-stream"}, 
            {".gif",    "image/gif"}, 
            {".gtar",   "application/x-gtar"}, 
            {".gz", "application/x-gzip"}, 
            {".h",  "text/plain"}, 
            {".htm",    "text/html"}, 
            {".html",   "text/html"}, 
            {".jar",    "application/java-archive"}, 
            {".java",   "text/plain"}, 
            {".jpeg",   "image/jpeg"}, 
            {".jpg",    "image/jpeg"}, 
            {".js", "application/x-javascript"}, 
            {".log",    "text/plain"}, 
            {".m3u",    "audio/x-mpegurl"}, 
            {".m4a",    "audio/mp4a-latm"}, 
            {".m4b",    "audio/mp4a-latm"}, 
            {".m4p",    "audio/mp4a-latm"}, 
            {".m4u",    "video/vnd.mpegurl"}, 
            {".m4v",    "video/x-m4v"},  
            {".mov",    "video/quicktime"}, 
            {".mp2",    "audio/x-mpeg"}, 
            {".mp3",    "audio/x-mpeg"}, 
            {".mp4",    "video/mp4"}, 
            {".mpc",    "application/vnd.mpohun.certificate"},        
            {".mpe",    "video/mpeg"},   
            {".mpeg",   "video/mpeg"},   
            {".mpg",    "video/mpeg"},   
            {".mpg4",   "video/mp4"},    
            {".mpga",   "audio/mpeg"}, 
            {".msg",    "application/vnd.ms-outlook"}, 
            {".ogg",    "audio/ogg"}, 
            {".pdf",    "application/pdf"}, 
            {".png",    "image/png"}, 
            {".pps",    "application/vnd.ms-powerpoint"}, 
            {".ppt",    "application/vnd.ms-powerpoint"}, 
            {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, 
            {".prop",   "text/plain"}, 
            {".rc", "text/plain"}, 
            {".rmvb",   "audio/x-pn-realaudio"}, 
            {".rtf",    "application/rtf"}, 
            {".sh", "text/plain"}, 
            {".tar",    "application/x-tar"},    
            {".tgz",    "application/x-compressed"},  
            {".txt",    "text/plain"}, 
            {".wav",    "audio/x-wav"}, 
            {".wma",    "audio/x-ms-wma"}, 
            {".wmv",    "audio/x-ms-wmv"}, 
            {".wps",    "application/vnd.ms-works"}, 
            {".xml",    "text/plain"}, 
            {".z",  "application/x-compress"}, 
            {".zip",    "application/x-zip-compressed"}, 
            {"",        "*/*"}   
        }; 

	boolean isExist(String path){
		File file = new File(path);
		if(file.exists()){
			return true;
		}
		
		return false;
	}
	
	Handler  mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(dialog!=null&&dialog.isShowing()) dialog.dismiss();
			switch (msg.what) {
			case 0://文件下载成功
//				ToastUtil.showToast(mContext, "下载文件成功！！！");
				//直接
				if(file!=null&&file.exists()){
					openFile(file);
				}
				break;
			case 1://文件下载失败
				ToastUtil.showToast(mContext, "读取文件失败！！！");
				break;
			default:
				break;
			}
			
		};
	};
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(fileList!=null &&fileList.size()>0){
			for (int i = 0; i < fileList.size(); i++) {
				if(fileList.get(i).exists()){
					fileList.get(i).delete();
				}
			}
		}
	}
	
	private boolean checkAppIsExist(String packageName){
		boolean isExist = false;
		 PackageInfo packageInfo;

	        try {
	            packageInfo = this.getPackageManager().getPackageInfo(
	            		packageName, 0);
	        } catch (NameNotFoundException e) {
	            packageInfo = null;
	            e.printStackTrace();
	        }
	        if(packageInfo !=null){
	        	isExist = true;
	        }


		return isExist;
	}
}
